package Controls;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonDataHelper {

	public static JSONArray getJsonObjectFromServer(String url){
		JSONArray jsonArrObj = new JSONArray();
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
	        }
			
			System.out.println("JSON STRING: " + sb.toString());
			
			JSONParser jsonParser = new JSONParser();
			if(jsonParser.parse(sb.toString()) instanceof JSONArray){
				jsonArrObj = (JSONArray) jsonParser.parse(sb.toString());
			}else if(jsonParser.parse(sb.toString()) instanceof JSONObject){
				JSONObject jsonObj = (JSONObject) jsonParser.parse(sb.toString());
				jsonArrObj.add(jsonObj);
			}
			
			return jsonArrObj;

		} catch (Exception e) {
			e.printStackTrace();
			return new JSONArray();
		}
		
	}
	
	public static String getImageContent(String path){
		String imageRoot = "http://superappli.wacontre.com/web/?target=image&image=";
		try {
			StringBuilder content = new StringBuilder();
			URL url = new URL(imageRoot + path);
			URLConnection urlConnection = url.openConnection();
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			String line;
			while ((line = bufferedReader.readLine()) != null)
		    {
				content.append(line + "\n");
		    }
		    bufferedReader.close();
			return content.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
}
